import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:photo_manager_image_provider/photo_manager_image_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'image_prview_page.dart';

class GalleryPage extends StatefulWidget {
  const GalleryPage({super.key});

  @override
  State<GalleryPage> createState() => _GalleryPageState();
}

class _GalleryPageState extends State<GalleryPage> {
  List<AssetEntity> images = [];
  bool isEditing = false;
  Set<AssetEntity> selectedImages = {};

  @override
  void initState() {
    super.initState();
    loadImages();
  }

  Future<void> loadImages() async {
    final permission = await PhotoManager.requestPermissionExtend();
    if (permission.isAuth) {
      List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
        type: RequestType.image,
      );
      List<AssetEntity> media =
          await albums[0].getAssetListPaged(page: 0, size: 100);
      setState(() {
        images = media;
      });
    } else {
      PhotoManager.openSetting();
    }
  }

  void onLongPressImage(AssetEntity asset) {
    setState(() {
      isEditing = true;
      selectedImages.add(asset);
    });
  }

  void onTapImage(AssetEntity asset) async {
    if (isEditing) {
      setState(() {
        if (selectedImages.contains(asset)) {
          selectedImages.remove(asset);
        } else {
          selectedImages.add(asset);
        }
      });
    } else {
      final file = await asset.file;
      if (file != null && mounted) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => ImagePreviewPage(
              images: images,
              initialIndex: images.indexOf(asset),
            ),
          ),
        );
      }
    }
  }

  void deleteSelected() async {
    for (var asset in selectedImages) {
      await PhotoManager.editor.deleteWithIds([asset.id]);
    }
    setState(() {
      isEditing = false;
      selectedImages.clear();
    });
    await loadImages();
  }

  void shareSelected() async {
    List<XFile> files = [];
    for (var asset in selectedImages) {
      final file = await asset.file;
      if (file != null) {
        files.add(XFile(file.path));
      }
    }
    if (files.isNotEmpty) {
      ShareParams params = ShareParams(files: files);
      SharePlus.instance.share(params);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(isEditing ? '选择了 ${selectedImages.length} 张' : '相册'),
        actions: isEditing
            ? [
                IconButton(
                    icon: const Icon(Icons.delete), onPressed: deleteSelected),
                IconButton(
                    icon: const Icon(Icons.share), onPressed: shareSelected),
                IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () {
                      setState(() {
                        isEditing = false;
                        selectedImages.clear();
                      });
                    }),
              ]
            : null,
      ),
      body: GridView.builder(
        itemCount: images.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          crossAxisSpacing: 2,
          mainAxisSpacing: 2,
        ),
        itemBuilder: (_, index) {
          final asset = images[index];
          return GestureDetector(
            onTap: () => onTapImage(asset),
            onLongPress: () => onLongPressImage(asset),
            child: Stack(
              fit: StackFit.expand,
              children: [
                AssetEntityImage(
                  asset,
                  thumbnailSize:
                      const ThumbnailSize.square(200), // Thumbnail size
                  isOriginal: false, // Use thumbnail instead of original
                  fit: BoxFit.cover,
                ),
                if (isEditing && selectedImages.contains(asset))
                  Container(
                    color: Colors.black.withOpacity(0.5),
                    child: const Center(
                        child: Icon(Icons.check_circle, color: Colors.white)),
                  ),
              ],
            ),
          );
        },
      ),
    );
  }
}
